<template>
  <div>
    <div class="app-container">
      <el-card class="searchTop" shadow="never">
        <div>
          <el-form :inline="true" :model="searchFormInline">
            <el-form-item label="PLC编号:">
              <el-input
                v-model="searchFormInline.plcId"
                placeholder="请输入PLC编号检索"
                clearable
                prefix-icon="Search"
                class="ei_1"
                style="width: 190px"
              />
            </el-form-item>
            <el-form-item label="PLC名称:">
              <el-input
                v-model="searchFormInline.plcName"
                placeholder="请输入PLC名称检索"
                clearable
                prefix-icon="Search"
                class="ei_1"
                style="width: 190px"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
              <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
      <el-card shadow="never">
        <div class="tableTop">
          <div class="buttonTop">
            <el-button type="primary" @click="handleAdd">+新增</el-button>
            <el-button type="danger" @click="handleDelList" style="padding: 5px">批量删除</el-button>
          </div>
        </div>
        <!-- 表格数据 -->
        <div class="table">
          <el-table
            :data="currentTableData"
            :fit="true"
            @selection-change="handleSelectionChange"
            :header-cell-style="{ textAlign: 'center' }"
          >
            <el-table-column type="selection" width="30" />
            <el-table-column type="index" label="排序" align="left" width="120px"></el-table-column>
            <el-table-column prop="plcId" label="PLC编号" align="left"></el-table-column>
            <el-table-column prop="plcName" label="PLC名称" align="left"></el-table-column>
            <el-table-column prop="ip" label="IP地址" align="left"></el-table-column>
            <el-table-column prop="port" label="端口" align="left"></el-table-column>
            <el-table-column fixed="right" align="center" label="操作">
              <!--Vue组件中定义一个插槽，row为当前行的数据，从父组件中拿到的，可以打印{{row}}查看 -->
              <!--如果#default="scope" scope为作用域对象，你可以拿到这个vue模版中的所有的对象和方法 -->
              <template #default="{ row }">
                <!-- {{ scope.row }} -->
                <el-button link type="primary" icon="Edit" @click="handleEdit(row)">编辑</el-button>
                <el-button link type="danger" icon="Delete" @click="handleRemove(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pager-foot">
          <!-- 分页 -->
          <el-pagination
            background
            :page-sizes="[8, 16, 32, 48]"
            :default-page-size="8"
            layout="total, sizes, prev, pager, next, jumper"
            :total="config.total"
            class="pager mt-5"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
    <!--新增和编辑用户 dialogVisible：隐藏显示对话框视图 -->
    <el-dialog
      v-model="dialogVisible"
      :title="getAction.action === 'add' ? '新增PLC信息' : '编辑PLC信息'"
      :before-close="handleClose"
      class="currentDialog"
      draggable
      style="width: 28%"
    >
      <!-- form的prop和v-model双向绑定的要一致，否则会回显数据-->
      <el-form
        class="dialog-form"
        :model="currentDialogForm"
        ref="currentDialogFormRef"
        label-width="85px"
        label-position="right"
        :rules="currentDialogFormRules"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="PLC编号:" prop="plcId">
              <el-input
                v-model="currentDialogForm.plcId"
                placeholder="请输入PLC编号"
                :disabled="getAction.action == 'edit'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="PLC名称:" prop="plcName">
              <el-input v-model="currentDialogForm.plcName" placeholder="请输入PLC名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="IP地址:" prop="ip">
              <el-input v-model="currentDialogForm.ip" placeholder="请输入IP地址" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="端口号:" prop="port">
              <el-input v-model="currentDialogForm.port" placeholder="请输入端口号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="dialog-foot">
          <el-form-item>
            <el-button @click="handleCancel">取消</el-button>
            <el-button type="primary" @click="onSubmit">确定</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from "vue"
import { Search, Refresh } from "@element-plus/icons-vue"
import { ElMessage, ElMessageBox, FormInstance } from "element-plus"
import { getPlcDataApi, deletePlcApi, batchDelPlcApi, addPlcApi, updatePlcApi } from "@/api/business/bus-plc"

// #region 定义属性值
/**分页配置 */
const config = reactive({
  total: 0,
  page: 1,
  size: 8,
  //进行搜索的关键词
  plcName: "",
  plcId: ""
})
/**搜索绑定 */
const searchFormInline = reactive({
  plcName: "",
  plcId: ""
})
/**当前表格数据 */
const currentTableData = ref()
/**保存批量删除的数据 */
let batchRemoveDatas = reactive([]) as any
/**对话框开关触发值 */
const dialogVisible = ref(false)
/**对话框标题值，复用对话框add或者edit */
const getAction = reactive({
  action: ""
})
/**对话框表单绑定的ref */
const currentDialogFormRef = ref()
/**新增编辑对话框下拉列表数据 */
const productionLineNameOptions = ref()
const plcNameOptions = ref()
// #endregion

onMounted(() => {
  getTableData(config)
})

// #region Table主页面相关操作
/** 关键字搜索*/
const handleSearch = () => {
  config.plcName = searchFormInline.plcName
  config.plcId = searchFormInline.plcId
  config.page = 1
  getTableData(config)
}
/**重置查询 */
const resetConfig = () => {
  Object.assign(config, {
    total: 0,
    page: 1,
    size: 8,
    plcName: "",
    plcId: ""
  })
}
/**重置搜索表单内容 */
const resetSearchFormInline = () => {
  Object.assign(searchFormInline, {
    plcName: "",
    plcId: ""
  })
}
/** 重置搜索*/
const resetSearch = () => {
  resetSearchFormInline()
  resetConfig()
  getTableData(config)
}

/**分页跳转 */
const handleCurrentChange = (val: number) => {
  config.page = val
  getTableData(config)
}
/** 改变每页条数 */
const handleSizeChange = (val: number) => {
  config.size = val
  getTableData(config)
}

/**获取表格数据 */
const getTableData = async (config: any) => {
  let res: any = await getPlcDataApi(config)
  if (res) {
    config.total = res.data.total
    currentTableData.value = res.data.dataList
  }
}

/** 新增按钮操作*/
const handleAdd = async () => {
  resetCurrentDialogForm()
  getAction.action = "add"
  dialogVisible.value = true
}
/** 编辑按钮操作*/
const handleEdit = async (row: any) => {
  getAction.action = "edit"
  dialogVisible.value = true
  nextTick(() => {
    Object.assign(currentDialogForm, row)
  })
}
/** 删除按钮操作*/
const handleRemove = (row: any) => {
  console.log("%c [ row ]-216", "font-size:13px; background:pink; color:#bf2c9f;", row)
  ElMessageBox.confirm("确定要删除吗", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      let res: any = await deletePlcApi({ id: row.plcId })
      if (res) {
        ElMessage({
          showClose: true,
          message: res.message,
          type: "success"
        })
        getTableData(config)
      }
    })
    .catch(() => {
      // catch error
    })
}
/** 批量选中*/
const handleSelectionChange = (val: any) => {
  console.log("%c [ val ]-447", "font-size:13px; background:pink; color:#bf2c9f;", val)
  batchRemoveDatas = []
  val.forEach((item: any) => {
    // 批量选中删除的主键值：唯一
    batchRemoveDatas.push(item.plcId)
  })
}
/** 批量删除操作*/
const handleDelList = () => {
  ElMessageBox.confirm("确定要删除吗", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      if (batchRemoveDatas.length !== 0) {
        console.log("%c [ ids ]-466", "font-size:13px; background:pink; color:#bf2c9f;", batchRemoveDatas)
        let res: any = await batchDelPlcApi(batchRemoveDatas)
        if (res) {
          ElMessage({
            showClose: true,
            message: res.message,
            type: "success"
          })
          getTableData(config)
          batchRemoveDatas = []
        }
      } else {
        ElMessage({
          showClose: true,
          message: "请选择要删除的数据",
          type: "warning"
        })
      }
    })
    .catch((err) => {
      console.log(err)
    })
}
// #endregion

// #region 对话框属性值和相关操作
/**对话框表单进行数据双向绑定 */
const currentDialogForm = reactive({
  plcId: "",
  plcName: "",
  ip: "",
  port: ""
})
/**对话框表单校验规则 */
const currentDialogFormRules = reactive({
  plcId: [
    {
      required: true,
      message: "请输入plc编号",
      trigger: "blur"
    }
  ],
  plcName: [
    {
      required: true,
      message: "请输入plc名称",
      trigger: "blur"
    }
  ],
  ip: [
    {
      required: true,
      message: "请输入plc的ip",
      trigger: "blur"
    }
  ],
  port: [
    {
      required: true,
      message: "请输入plc的端口号",
      trigger: "blur"
    }
  ]
})

/**重置对话框表单数据，防止数据回显 */
const resetCurrentDialogForm = () => {
  Object.assign(currentDialogForm, {
    // 重置表单数据
    plcId: "",
    plcName: "",
    ip: "",
    port: ""
  })
}
/** 点击x号关闭对话框*/
const handleClose = (done: () => void) => {
  ElMessageBox.confirm("确定关闭吗?", {
    confirmButtonText: "确定",
    cancelButtonText: "取消"
  })
    .then(() => {
      // 确定关闭后需要的操作处理
      currentDialogFormRef.value.resetFields()
      done()
    })
    .catch(() => {
      // catch error
    })
}

/** 点击取消按钮关闭对话框*/
const handleCancel = () => {
  dialogVisible.value = false
  currentDialogFormRef.value.resetFields()
}

/** 对话框提交保存数据*/
const onSubmit = () => {
  // 表单内容验证，表单的ref属性拿到表单，使用el-api校验
  currentDialogFormRef.value.validate(async (valid: FormInstance | undefined) => {
    if (valid) {
      // 验证通过，发送新增或修改请求
      if (getAction.action == "add") {
        const { plcId, plcName, ip, port } = currentDialogForm
        let addCurrentDialogForm = {
          plcId: plcId,
          plcName: plcName,
          ip: ip,
          port: port
        }
        let res: any = await addPlcApi(addCurrentDialogForm)
        if (res) {
          ElMessage({
            type: "success",
            message: res.message
          })
          currentDialogFormRef.value.resetFields()
          dialogVisible.value = false
          getTableData(config)
        }
      } else {
        let editCurrentDialogForm = { ...currentDialogForm }
        let res: any = await updatePlcApi(editCurrentDialogForm)
        if (res) {
          ElMessage({
            type: "success",
            message: res.message
          })
          currentDialogFormRef.value.resetFields()
          dialogVisible.value = false
          getTableData(config)
        }
      }
    } else {
      ElMessage.error("请填写完整信息")
    }
  })
}
// #endregion
</script>
<style lang="scss" scoped>
.add-container {
  padding: 20px;
}
.searchTop {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}
.tableTop {
  margin-bottom: 20px;
}
.table {
  display: flex;
  margin-bottom: 10px;
}
.pager-foot {
  display: flex;
  justify-content: flex-end;
}
.dialog-foot {
  display: flex;
  justify-content: end;
}
.form_description {
  :deep(.el-textarea__inner) {
    height: 100px;
  }
}
.dialog-form {
  margin-top: 20px;
}
</style>
